package com.example.mdoncall;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * 
 * @author Anthony Maniquiz & Laine Nicolas (Smart Telecom Inc. OJT) 
 * @version 1
 * 
 */

public class PersonDbHelper extends SQLiteOpenHelper {
	
	 // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;
 
    // Database Name
    private static final String DATABASE_NAME = "contactsManager";
 
    // Contacts table name
    private static final String TABLE_CONTACTS = "contacts";
 
    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_FNAME = "fname";
    private static final String KEY_LNAME = "lname";
    private static final String KEY_MNAME = "mname";
    private static final String KEY_BDAY = "bday";
    private static final String KEY_GENDER = "gender";
    private static final String KEY_PH_NO = "phone_number";
    
    private static final String KEY_STREET = "street";
    private static final String KEY_CITY = "city";
    
    private static final String KEY_CONDITION = "condition";
    private static final String KEY_ALLERGY = "allergy";
    private static final String KEY_MEDICATION = "medication";
 
    public PersonDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_FNAME + " TEXT,"
                + KEY_LNAME + " TEXT," + KEY_MNAME + " TEXT," + KEY_BDAY + " TEXT,"
                + KEY_GENDER + " TEXT, " + KEY_PH_NO + " TEXT, " + KEY_STREET + " TEXT, " 
                + KEY_CITY + " TEXT, " + KEY_CONDITION + " TEXT, " + KEY_ALLERGY + " TEXT, " 
                + KEY_MEDICATION + " TEXT" + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }
 
    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
 
        // Create tables again
        onCreate(db);
    }
    
 // Adding new contact
    public void addContact(Contact contact) {
    	SQLiteDatabase db = this.getWritableDatabase();
    	 
        ContentValues values = new ContentValues();
        values.put(KEY_FNAME, contact.getFname());
        values.put(KEY_LNAME, contact.getLname());
        values.put(KEY_MNAME, contact.getMname());
        values.put(KEY_BDAY, contact.getBday());
        values.put(KEY_GENDER, contact.getGender());
        values.put(KEY_PH_NO, contact.getPhoneNumber());
        
        values.put(KEY_STREET, contact.getStreet());
        values.put(KEY_CITY, contact.getCity());
        
        values.put(KEY_CONDITION, contact.getCondition());
        values.put(KEY_ALLERGY, contact.getAllergy());
        values.put(KEY_MEDICATION, contact.getMedication());
     
        // Inserting Row
        db.insert(TABLE_CONTACTS, null, values);
        db.close(); // Closing database connection
    }
     
    // Getting single contact
    public Contact getContact(int id) {
    	SQLiteDatabase db = this.getReadableDatabase();
    	 
        Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
                KEY_FNAME, KEY_LNAME, KEY_MNAME, KEY_BDAY, KEY_GENDER, KEY_PH_NO, KEY_STREET, KEY_CITY,
                KEY_CONDITION, KEY_ALLERGY, KEY_MEDICATION }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();
     
        Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), 
                cursor.getString(5), cursor.getString(6), cursor.getString(7), cursor.getString(8),
                cursor.getString(9), cursor.getString(10), cursor.getString(11) );
        // return contact
        return contact;
    }
     
    // Getting All Contacts
    public List<Contact> getAllContacts() {
    	List<Contact> contactList = new ArrayList<Contact>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;
     
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
		
		db.rawQuery("SELECT " + KEY_LNAME 
		           + " FROM " +TABLE_CONTACTS 
		        +" ORDER BY "+KEY_LNAME+" COLLATE NOCASE ASC;", null);
        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Contact contact = new Contact();
                contact.setID(Integer.parseInt(cursor.getString(0)));
                contact.setFname(cursor.getString(1));
                contact.setLname(cursor.getString(2));
                contact.setMname(cursor.getString(3));
                contact.setBday(cursor.getString(4));
                contact.setGender(cursor.getString(5));
                contact.setPhoneNumber(cursor.getString(6));
                
                contact.setStreet(cursor.getString(7));
                contact.setCity(cursor.getString(8));
                
                contact.setCondition(cursor.getString(9));
                contact.setAllergy(cursor.getString(10));
                contact.setMedication(cursor.getString(11));
                
                // Adding contact to list
                contactList.add(contact);
            } while (cursor.moveToNext());
        }
     
        // return contact list
        return contactList;
        
    }
     
    // Getting contacts Count
    public int getContactsCount() {
    	String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();
 
        // return count
        return cursor.getCount();
    }
    // Updating single contact
    public int updateContact(Contact contact, int KEY_ID) {
    	SQLiteDatabase db = this.getWritableDatabase();
    	
        ContentValues values = new ContentValues();
        values.put(KEY_FNAME, contact.getFname());
        values.put(KEY_LNAME, contact.getLname());
        values.put(KEY_MNAME, contact.getMname());
        values.put(KEY_BDAY, contact.getBday());
        values.put(KEY_GENDER, contact.getGender());
        values.put(KEY_PH_NO, contact.getPhoneNumber());
        
        values.put(KEY_STREET, contact.getStreet());
        values.put(KEY_CITY, contact.getCity());
        
        values.put(KEY_CONDITION, contact.getCondition());
        values.put(KEY_ALLERGY, contact.getAllergy());
        values.put(KEY_MEDICATION, contact.getMedication());
        
        String where = "id" + "=" + KEY_ID;
        
        // updating row
        /*return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",new String[] { String.valueOf(contact.getID()) });*/
        return db.update(TABLE_CONTACTS, values, where, null);
        
    }
     
    // Deleting single contact
    public void deleteContact(Contact contact) {
    	SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
        db.close();
    }
    
    
    // ************* This method is still to be tested *****************
    // Getting All Contacts Test (Apply order by clause)
    public List<Contact> getAllContactsTest(String strTest) {
    	List<Contact> contactList = new ArrayList<Contact>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS + " WHERE " + KEY_PH_NO + " = " +strTest;
     
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
     
        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Contact contact = new Contact();
                contact.setID(Integer.parseInt(cursor.getString(0)));
                contact.setFname(cursor.getString(1));
                contact.setLname(cursor.getString(2));
                contact.setMname(cursor.getString(3));
                contact.setBday(cursor.getString(4));
                contact.setGender(cursor.getString(5));
                contact.setPhoneNumber(cursor.getString(6));
                
                contact.setStreet(cursor.getString(7));
                contact.setCity(cursor.getString(8));
                
                contact.setCondition(cursor.getString(9));
                contact.setAllergy(cursor.getString(10));
                contact.setMedication(cursor.getString(11));
                
                // Adding contact to list
                contactList.add(contact);
            } while (cursor.moveToNext());
        }
     
        // return contact list
        return contactList;
        
    }
}
